package com.irdstudio.efp.esb.api.service.psd.credit;

import com.alibaba.fastjson.JSON;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.irdstudio.efp.basic.framework.mq.constant.TagEnums;
import com.irdstudio.efp.basic.framework.mq.constant.TopicEnums;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.esb.api.bean.psd.credit.req.PsdCreditBackReqBean;
import com.irdstudio.efp.esb.api.service.common.repository.NlsRepository;
import com.irdstudio.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.irdstudio.efp.nls.service.common.rules.credit.HasCreditInfoApproveRule;
import com.irdstudio.efp.nls.service.common.rules.credit.HasCreditInfoRule;
import com.irdstudio.efp.nls.service.facade.NlsPublicService;
import com.irdstudio.efp.nls.service.facade.psd.NlsCreditApprovalInfoService;
import com.irdstudio.efp.nls.service.facade.psd.PreNlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.psd.NlsCreditApprovalInfoVO;
import com.irdstudio.efp.nls.service.vo.psd.PreNlsCreditInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/12/6
 * 功能描述:
 * 修改日期:2019/12/6
 * 修改描述:
 */
@Service("psdCreditBackService")
public class PsdCreditBackService {
    private static Logger logger = LoggerFactory.getLogger(PsdCreditBackService.class);

    public void processApply(PsdCreditBackReqBean psdCreditBackReqBean) throws BizException {
        String mobile = null;
        try {
            NlsCreditInfoVO selectCreditInfo = nlsRepository.getNlsCreditInfoBySeq(psdCreditBackReqBean.getCrAppSrlNo());
            NlsCreditApprovalInfoVO nlsCreditInfoApprovalVO = nlsRepository.getNlsCreditInfoApprovalVO(psdCreditBackReqBean.getCrAppSrlNo());

            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.checkFor(new HasCreditInfoRule(selectCreditInfo));
            nlsCreditInfoVO.checkFor(new HasCreditInfoApproveRule(nlsCreditInfoApprovalVO));
            //更新企业类型字段到预授信信息中
            updateEnTp(psdCreditBackReqBean,selectCreditInfo);
            mobile = selectCreditInfo.getIndivMobile();
            //失败时候下发短信
            updateCreditApproveInfo(psdCreditBackReqBean, nlsCreditInfoApprovalVO,selectCreditInfo);
            updateCreditInfo(psdCreditBackReqBean, selectCreditInfo);
            sendMessageIfApproveAccess(psdCreditBackReqBean, selectCreditInfo);
            if (isApproveFailure(psdCreditBackReqBean) ||  isApproveLmtZero(psdCreditBackReqBean)) {
                nlsPublicService.sendFailMesage(mobile);
            }

        } catch (BizException e) {
            nlsPublicService.sendFailMesage(mobile);
            logger.error(e.getMessage());
            throw e;
        } catch (UnsupportedEncodingException e) {
            logger.error("普税贷用信申请发送消息到mq出现异常", e.getMessage());
            e.printStackTrace();
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "普税贷风控审批接口发送消息到mq出现异常");
        } finally {
        }
    }

    @Autowired
    private PreNlsCreditInfoService preNlsCreditInfoService;

    private void updateEnTp(PsdCreditBackReqBean psdCreditBackReqBean, NlsCreditInfoVO selectCreditInfo) {
        logger.info("授信申请流水号：{}，从大数据风控获取到的企业类型为：{}",selectCreditInfo.getLmtApplySeq(),psdCreditBackReqBean.getEnTp());
        try {
            if (StringUtils.isNotEmpty(psdCreditBackReqBean.getEnTp())) {
                PreNlsCreditInfoVO pkParam = new PreNlsCreditInfoVO();
                pkParam.setApplySeq(selectCreditInfo.getPreLmtApplySeq());
                PreNlsCreditInfoVO preNlsCreditInfoVO = preNlsCreditInfoService.queryByPk(pkParam);
                if (!Objects.isNull(preNlsCreditInfoVO)) {
                    preNlsCreditInfoVO.setBkColumn1(psdCreditBackReqBean.getEnTp());
                    preNlsCreditInfoService.updateByPk(preNlsCreditInfoVO);
                }
            }
        } catch (Exception e) {
            logger.error("更新企业类型数据到预授信申请表发生异常【{}】,授信申请流水号为：【{}】，预授信申请流水号为：【{}】，风控返回的企业类型为【{}】。", e.getMessage(), selectCreditInfo.getLmtApplySeq(), selectCreditInfo.getPreLmtApplySeq(), psdCreditBackReqBean.getEnTp());
        }
    }

    private void updateCreditApproveInfo(PsdCreditBackReqBean psdCreditBackReqBean, NlsCreditApprovalInfoVO nlsCreditInfoApprovalVO, NlsCreditInfoVO selectCreditInfo) throws BizException {
        nlsCreditInfoApprovalVO.setApprResult(psdCreditBackReqBean.getAprvlRsltFlg());
        nlsCreditInfoApprovalVO.setRefuseCode(psdCreditBackReqBean.getRfsCd());
        nlsCreditInfoApprovalVO.setIsSendToTax("N");
        nlsCreditInfoApprovalVO.setApproveTime(new Date());
        if (isApproveFailure(psdCreditBackReqBean)) {
            nlsCreditInfoApprovalVO.setRefuseMsg("纳税人授信失败");
        }else if (isApproveException(psdCreditBackReqBean)) {
            nlsCreditInfoApprovalVO.setRefuseMsg("纳税人请重新申请授信");
        }
        if (isApproveAccess(psdCreditBackReqBean)) {
            nlsCreditInfoApprovalVO.setApproveAmt(psdCreditBackReqBean.getLoanAplLmt());
            nlsCreditInfoApprovalVO.setApplyRateY(Optional.ofNullable(psdCreditBackReqBean.getYrRate()).orElse(selectCreditInfo.getApplyRateY()));
        }
        int result = nlsCreditApprovalInfoService.updateByPrimaryKey(nlsCreditInfoApprovalVO);
        if (result != 1) {
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "普税贷更新授信审批信息失败");
        }
    }

    private void updateCreditInfo(PsdCreditBackReqBean psdCreditBackReqBean, NlsCreditInfoVO nlsCreditInfoVO) throws BizException {
        nlsCreditInfoVO.setApproveAmt(psdCreditBackReqBean.getLoanAplLmt());
        nlsCreditInfoVO.setApplyRateY(psdCreditBackReqBean.getYrRate());
        nlsCreditInfoVO.setApproveRateY(Optional.ofNullable(psdCreditBackReqBean.getYrRate()).orElse(nlsCreditInfoVO.getApplyRateY()));
        if (isApproveFailure(psdCreditBackReqBean)) {
            nlsCreditInfoVO.setApprvSts("03");
            nlsCreditInfoVO.setRefuseCause("准入失败");
        }else if (isApproveAccess(psdCreditBackReqBean) && isApproveLmtZero(psdCreditBackReqBean)) {
            nlsCreditInfoVO.setApprvSts("03");
            nlsCreditInfoVO.setRefuseCause("准入失败 风控审批金额为空");
        } else if (isApproveException(psdCreditBackReqBean)) {
            nlsCreditInfoVO.setApprvSts("03");
            nlsCreditInfoVO.setRefuseCause("风控系统异常");
        }
        nlsCreditInfoVO.setApprvDate(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
        int result = nlsCreditInfoService.updateByPk(nlsCreditInfoVO);
        if (result != 1) {
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "普税贷更新授信信息失败");
        }
    }

    private boolean isApproveLmtZero(PsdCreditBackReqBean psdCreditBackReqBean) {
        return Objects.isNull(psdCreditBackReqBean.getLoanAplLmt()) || BigDecimal.ZERO.compareTo(psdCreditBackReqBean.getLoanAplLmt()) == 0;
    }

    private void sendMessageIfApproveAccess(PsdCreditBackReqBean psdCreditBackReqBean, NlsCreditInfoVO nlsCreditInfoVO) throws UnsupportedEncodingException {
        if (isApproveAccess(psdCreditBackReqBean) && !isApproveLmtZero(psdCreditBackReqBean)) {
            nlsCreditInfoVO.setSoltStage(PrdAdaptedSoltEnums.PsdSoltStageEnum.CREDIT.getVALUE());
            producerService.sendMsg(new Message(TopicEnums.QUEUE_TASK_CREDIT_TOPIC.getTopicId(), TagEnums.TAG_QUEUE_CREDIT_TASK.getTagId(), nlsCreditInfoVO.getLmtApplySeq() + "-1" + Integer.toString((int)((Math.random()*9+1)*100)),
                    JSON.toJSONString(nlsCreditInfoVO).getBytes("UTF-8")));
        }
    }

    private boolean isApproveAccess(PsdCreditBackReqBean psdApplyBackReqBean) {
        return "Y".equals(psdApplyBackReqBean.getAprvlRsltFlg().trim()) ? true : false;
    }
    private boolean isApproveException(PsdCreditBackReqBean psdApplyBackReqBean) {
        return "E".equals(psdApplyBackReqBean.getAprvlRsltFlg().trim()) ? true : false;
    }
    private boolean isApproveFailure(PsdCreditBackReqBean psdApplyBackReqBean) {
        return "N".equals(psdApplyBackReqBean.getAprvlRsltFlg().trim()) ? true : false;
    }

    @Autowired
    private NlsRepository nlsRepository;
    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;
    @Autowired
    @Qualifier("nlsCreditApprovalInfoService")
    private NlsCreditApprovalInfoService nlsCreditApprovalInfoService;
    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;
    @Autowired
    @Qualifier("nlsPublicService")
    private NlsPublicService nlsPublicService;
    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;
}
